package com.ggshily.swf.abc;

import java.io.DataInput;
import java.io.IOException;

public class ABCUtil
{
	public static final char BACKSLASH = '/';

	public static short readU8(DataInput dis) throws IOException
	{
		return (short) (dis.readByte() & 0xFF);
	}

	public static int readU16(DataInput dis) throws IOException
	{
		return dis.readByte() | (dis.readByte() << 8);
	}
	
	public static int readU30(DataInput dis) throws IOException
	{
		int result = 0;
		byte data = 0;
		int i = 0;
		do
		{
			data &= (0x7F << (i * 8));
			data = dis.readByte();
			result |= (data & 0x7F) << (i++ * 7);
		} while(((data >>> 7) & 0x1) == 1);
		return result;
	}

	public static int readS32(DataInput dis) throws IOException
	{
		int result = 0;
		byte data = 0;
		int i = 0;
		do
		{
			data &= (0x7F << (i * 8));
			data = dis.readByte();
			result |= (data & 0x7F) << (i++ * 8);
		} while(((data >> 7) & 0x1) == 1);
		result |= ((data >> 6) & 0x1) << 31;
		return result;
	}

	public static long readU32(DataInput dis) throws IOException
	{
		long result = 0;
		byte data = 0;
		int i = 0;
		do
		{
			data &= (0x7F << (i * 8));
			data = dis.readByte();
			result |= (data & 0x7F) << (i++ * 8);
		} while(((data >> 7) & 0x1) == 1);
		return result;
	}

	public static double readD64(DataInput dis) throws IOException
	{
		return dis.readDouble();
	}

	public static String readUtf8(DataInput di) throws IOException
	{
		StringBuilder sb = new StringBuilder();
		char c;
		while((c = (char) di.readByte()) != 0)
		{
			sb.append(c);
		}
		return sb.toString();
	}

	public static String readUtf8(DataInput dis, int size)
			throws IOException
	{
		byte[] bytes = new byte[size];
		dis.readFully(bytes);
		return new String(bytes);
	}

	public static <T> void readArray(IABCData[] ary, Class<T> class1, DataInput di, int length)
			throws InstantiationException, IllegalAccessException, IOException
	{
		for(int i = 0; i < length; i++)
		{
			ary[i] = (IABCData) class1.newInstance();
			ary[i].parseInput(di);
		}
	}

	public static <T> void readArray(IABCData[] ary, Class<T> class1, DataInput di, int length, ABCFile file)
			throws InstantiationException, IllegalAccessException, IOException
	{

		for(int i = 0; i < length; i++)
		{
			ary[i] = (IABCData) class1.newInstance();
			ary[i].parseInput(di, file);
		}
	}

	public static String getQName(String multiname)
	{
		if(multiname.lastIndexOf(BACKSLASH) >= 0)
		{
			return multiname.substring(multiname.lastIndexOf(BACKSLASH) + 1);
		}
		return multiname;
	}
}
